package leetcode.offer_two_special.backtrack;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @author mazouri
 * @create 2021-09-19 19:47
 */
public class _84_permuteUnique {
    List<List<Integer>> res = new LinkedList<>();
    LinkedList<Integer> track = new LinkedList<>();
    boolean[] visited;
    int[] nums;

    public List<List<Integer>> permuteUnique(int[] nums) {
        this.nums = nums;
        this.visited = new boolean[nums.length];
        Arrays.sort(this.nums);
        backtrack();
        return res;
    }

    private void backtrack() {
        if (track.size() == nums.length) {
            res.add(new LinkedList<>(track));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            //如果之前访问过该元素，剪掉
            if (visited[i]) continue;
            //如果前一个元素访问过且和这个元素相等，剪掉
            if (i > 0 && nums[i] == nums[i - 1] && visited[i - 1]) continue;

            visited[i] = true;
            track.add(nums[i]);
            backtrack();
            track.removeLast();
            visited[i] = false;
        }
    }
}
